package com.cs171.market.controller;

import com.cs171.market.entity.Student;
import com.cs171.market.Repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@CrossOrigin
@RestController
public class StudentController {
    // RESTful api 将资源放在同一路径下的前后端路由规范
    @Autowired
    private StudentRepository repository;

    /**
     * 1.获取学生所有信息
     */
    @GetMapping("/students")
    public List<Student> getAll(){
       return repository.findAll(); // JpaRepository 实现了增删改查接口
    }

    /**
     * 2.创建一条学生信息
     * @return
     */
    @PostMapping("/students") // post请求 用表单传值(body->form-data)
    public Student create(@RequestParam("name")String name, @RequestParam("sex")String sex, @RequestParam("fee")BigDecimal fee){
        Student student = new Student();
        student.setName(name);
        student.setSex(sex);
        student.setFee(fee);

        return repository.save(student);
    }

    /**
     * 3.通过id查找一个学生
     */
    @GetMapping("/students/{id}")
    public Student findById(@PathVariable("id")Integer id){
        return repository.findById(id).orElse(null); // findById()返回Optional类，应用orElse如果查询不到返回确定的值
    }

    /**
     * 4.通过学号更新学生信息
     */
    @PutMapping("/students/{id}")
    public Student update(@PathVariable("id")Integer id,
                          @RequestParam(value = "name", required = false)String name,
                          @RequestParam(value = "sex", required = false)String sex,
                          @RequestParam(value = "fee", required = false)BigDecimal fee){
        Student updateStudent =  repository.findById(id).orElse(null);
        updateStudent.setName(name!=null?name:updateStudent.getName());
        updateStudent.setSex(sex!=null?sex:updateStudent.getSex());
        updateStudent.setFee(fee!=null?fee:updateStudent.getFee());
        return repository.save(updateStudent); // findById()返回Optional类，应用orElse如果查询不到返回确定的值
    }
}
